package wh.coach.dynamicproxy;

import java.lang.reflect.Proxy;

public class Main {

    public static void main(String[] args) {
        //静态代理
        HelloService helloService = createStaticProxy();
        helloService.sayHello("Tom");
        //动态代理
        helloService = createDynamicProxy();
        helloService.sayHello("Tom");
    }

    private static HelloService createDynamicProxy() {
        //Proxy.newProxyInstance方法会创建出HelloService接口实现类的字节码，并创建这个类的实例
        final Class<HelloService> serviceClass = HelloService.class;
        return (HelloService) Proxy.newProxyInstance(
                serviceClass.getClassLoader(),
                new Class<?>[]{serviceClass},
                new HelloServiceInvocationHandler()
        );
    }

    private static HelloService createStaticProxy() {
        //jvm会从classpath下面查找HelloService的实现类
        //找到后，jvm就可以创建这个类的实例
        return new HelloServiceImpl();
    }
}
